package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.tikhub.TikhubXhsAwemeCommentListData;
import com.showsu.editor.entity.tikhub.TikhubXhsAwemeCommentListResp;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.GsonFailSafeArrayJsonDeserializer;
import com.showsu.editor.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description: https://documenter.getpostman.com/view/667970/2sAYdcrs3X#f13a093e-34b2-4af8-a67b-660b485fad67
 * @Date: Created in 06:43 2025/3/8
 * @Modified By:
 */
@Slf4j
@Component
public class DatapiUtl {

    private static final int timeout = 20000;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    private static final Integer pageSize = 20;
    private static final Integer totalLimit = 60;

    /**
     * gson反序列化时，用于忽略array的错误。因为有的时候字段返回为空，我们认为是可以接受的。
     */
    private GsonFailSafeArrayJsonDeserializer gsonFailSafeArrayJsonDeserializer = new GsonFailSafeArrayJsonDeserializer();

    @Value("${datapi.url}")
    private String baseUrl;

    @Value("${datapi.token}")
    private String token;

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 获取xhs笔记评论数据（带live）
     * @param noteId
     * @param cursor 首页传空，翻页是用上一页的最后一个评论id
     * @param interfaceId
     * @return
     */
    public TikhubXhsAwemeCommentListResp getXhsAwemeCommentList(String noteId, String cursor, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        TikhubXhsAwemeCommentListResp result = new TikhubXhsAwemeCommentListResp();
        Type type = new TypeToken<TikhubXhsAwemeCommentListData>(){}.getType();
        Gson gson = new Gson();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(baseUrl).append("/xhsapi/commentByApp?token=")
                            .append(token).append("&noteId=").append(noteId).append("&cursor=").append(cursor);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("DatapiUtl查询xhs笔记评论-响应耗时:{}-noteId:{},cursor:{}", System.currentTimeMillis() - start, noteId, cursor);
                    TikhubXhsAwemeCommentListData temp = gson.fromJson(responseInner, type);
                    //如果平台那边报错再重试一次
                    if (temp == null || ( temp.getCode() != null && temp.getCode() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error(String.format("DatapiUtl.getXhsAwemeCommentList(String,String,Long) error, noteId:{%s},cursor:{%d}", noteId, cursor), e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).append(",noteId").append(noteId).toString());
            return null;
        }
        try {
            TikhubXhsAwemeCommentListData tikhubXhsAwemeCommentListData = gson.fromJson(response, type);
            tikhubXhsAwemeCommentListData.initVideoInfo();
            //这个接口要把最后一条评论的id作为下一页请求的cursor
            if (tikhubXhsAwemeCommentListData.getData() != null && ! CollectionUtils.isEmpty(tikhubXhsAwemeCommentListData.getData().getComments())) {
                tikhubXhsAwemeCommentListData.getData().setCursor(
                        tikhubXhsAwemeCommentListData.getData().getComments().get(
                                tikhubXhsAwemeCommentListData.getData().getComments().size() - 1
                        ).getId());
            }
            result.setData(tikhubXhsAwemeCommentListData);
        } catch (Exception e) {
            log.error(String.format("DatapiUtl.getXhsAwemeCommentList(String,String,Long) convert error, noteId:{%s},cursor:{%d}", noteId, cursor), e);
        }
        return result;
    }

    public static void main(String[] args) {
        //String response = HttpUtil.get("http://datapi.top/xhsapi/feedApp?noteId=67c13feb000000000302a5d7&token=Trilaron");
        //String response = HttpUtil.get("http://datapi.top/xhsapi/search?sort=general&note_type=0&keywords=刘德华&token=Trilaron&page=1");
        String response = HttpUtil.get("http://datapi.top/xhsapi/commentByApp?noteId=67ca8d69000000002902ea0f&token=Trilaron&cursor");
        System.out.println(response);
        Type type = new TypeToken<TikhubXhsAwemeCommentListData>(){}.getType();
        Gson gson = new Gson();
        TikhubXhsAwemeCommentListData result = gson.fromJson(response, type);
        result.initVideoInfo();
        System.out.println(JSON.toJSONString(result));
    }
}
